home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Combine zero-offset with unit-offset arrays ?
- Date: 4 Mar 1996 09:57:25 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4hfau5INNme5@keats.ugrad.cs.ubc.ca>
- References: <4hes0h$52qi@info4.rus.uni-stuttgart.de>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4hes0h$52qi@info4.rus.uni-stuttgart.de>,
- Markus Heller <Markus.Heller@studbox.uni-stuttgart.de> wrote:
- >Hi,
- >
- >I want to combine my code (using zero-offset arrays) with
- >code using unit-offset arrays.
- >The FAQ - 2.16 mentions a method used "in old editions of
- >Numerical Recipes in C" that leads to undefined behavior.
- >Unfortunately there's no alternative mentioned.
- >E.g.:
- >
- >void somefunction( float fa[], int n);
- >
- >int main(void)
- >{
- > float a[10]; /* zero offset: a[0] .. a[9] */
- > int n=10;
- >
- > somefunction( a-1, 10 ); /* method suggested by Numerical Recipes,
- > 2nd edition */
- >}
- >
- >void somefunction( float fa[], int n)
- >{
- > /* do something with a, assuming unit-offset: a[1]..a[10] */
- >}
- >
- >
- >Which alternatives are possible to the above mentioned method ?
-
- Try this:
-
- void somefunction(float fa[], int n)
- #define fa (fa-1)
- {
- int foo = fa[1];
- }
-
- int main(void)
- {
- float a[10];
-
- somefunction(a,sizeof(a));
- }
-
- >(Is the method still leasding to undefined behavior ?)
-
- The expression fa[1] undergoes pre-processing, and becomes (fa-1)[1].
-
- Of course, this is just equivalent to *((fa-1) + 1). This is still undefined,
- though it's syntactically convenient. What you want is to add the 1 first, then
- subtract, in other words: *((fa+1) - 1). For this, you must break with the nice
- syntax and go for this:
-
- #define fa(x) (fa[x-1])
- {
- int foo = fa(1);
- }
-
- which now gives you fa[1-1], which is *((fa) + 1 - 1). This is defined. The
- standard allows you generate a pointer which references one element past the
- end of the array, thus if you put in the subscript 10, you would have
- *((fa) + 10 - 1). ANSI condones the generation of a pointer to the non-existant
- element of the array that is conceptually one index past the last one, in
- order to support certain common coding idioms.
- --
-
-